# -*- coding: utf-8 -*-
"""
Chapter 6: Application Organization with Blueprints

This demo covers:
- Creating and organizing Flask applications with Blueprints
- Modular application structure
- URL prefixing for organized routing
- Template and static file organization
- Error handling within blueprints
"""

import os
import secrets
from flask import Flask

# Import blueprints
from main import main
from blog import blog
from admin import admin
from api import api


def create_app():
    """Application factory function."""
    app = Flask(__name__)
    app.secret_key = os.getenv('SECRET_KEY', secrets.token_hex(16))
    
    # Register blueprints
    app.register_blueprint(main)
    app.register_blueprint(blog)
    app.register_blueprint(admin)
    app.register_blueprint(api)
    
    # Global error handlers
    @app.errorhandler(404)
    def not_found(error):
        return '<h1>Page Not Found</h1><p>The requested page could not be found.</p>', 404
    
    @app.errorhandler(500)
    def internal_error(error):
        return '<h1>Internal Server Error</h1><p>An unexpected error occurred.</p>', 500
    
    return app


# Create the app instance
app = create_app()


if __name__ == '__main__':
    app.run(
        host=os.getenv('FLASK_HOST', '127.0.0.1'),
        port=int(os.getenv('FLASK_PORT', 5000)),
        debug=os.getenv('FLASK_DEBUG', 'True').lower() == 'true'
    )